package com.woniuxy.woniubook.intercepters;

import com.woniuxy.woniubook.uitl.CookieUtil;
import com.woniuxy.woniubook.uitl.JwtUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class PermissionIntercepter implements HandlerInterceptor {

    @Autowired
    RedisTemplate<String ,Object> redisTemplate ;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //Object userInfo = request.getSession().getAttribute("userInfo");
        String user_token = CookieUtil.getToken(request, "user_token");

        String servletPath = request.getServletPath();
        System.out.println(servletPath);
        if (user_token == null) {
            request.setAttribute("errorInfo","请先登录!");
            request.getRequestDispatcher("/login.html").forward(request,response);
            return  false ;
        }
        //如果 token过期 或者 token 被仿制
        if (user_token != null) {
            //从redis中获取 账户
            String myaccount = (String) redisTemplate.opsForValue().get(user_token);

            String user_token1 = (String) redisTemplate.opsForValue().get(myaccount+"_user_token");
            if (user_token1 == null) {
                // 不合理的
                request.setAttribute("errorInfo","登录过期，请重新登录!");
                request.getRequestDispatcher("/login.html").forward(request,response);
                return  false ;
            }
            //设置redis的token
            redisTemplate.opsForValue().set(myaccount+"_user_token",user_token1,30*60, TimeUnit.SECONDS);

            try {
                JwtUtils.parseToken(user_token);
            }catch (ExpiredJwtException e) {
                //重新生成 token
                String account = JwtUtils.getAccount(user_token1);
                String token = JwtUtils.createToken(account, 15);
                CookieUtil.addCookie(request,response,token);

                //重置redis中账户
                redisTemplate.delete(user_token);
                redisTemplate.opsForValue().set(token,account);
                return  true ;
            }catch (RuntimeException e) {
                request.setAttribute("errorInfo","非法登录，请重新登录!");
                request.getRequestDispatcher("/login.html").forward(request,response);
                e.printStackTrace();
                return  false ;
            }
        }
        return true ;
    }
}
